package com.hsnr.findyourbuddy;

import java.io.IOException;
import java.util.HashMap;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

public class UpdateService extends Service implements LocationListener {

    private LocationManager locationManager;
    private String provider;
    private HashMap<String, String> coordinates;
    private Location location;
    private double longitude, latitude;
    private int delay; // eine Minute Wartezeit. Bei Bedarf anpassen
    private boolean updateServiceEnabled;
    private boolean runFlag;
    private Updater updater;
    private final String TAG = "MapUpdateService";

    public void onCreate() {

        super.onCreate();
        Log.d(TAG, " onCreated");
        final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        this.updateServiceEnabled = sharedPrefs.getBoolean("prefUpdateService", true); //$NON-NLS-1$
        if (this.updateServiceEnabled) { 
            String minutes = sharedPrefs.getString("prefMinutes", "10");
            if (minutes.equals(""))
                minutes = "10";
            int intervall = Integer.parseInt(minutes) * 60000;
            this.delay = intervall;
            this.updater = new Updater();
        }

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        super.onStartCommand(intent, flags, startId);

        if (!runFlag) {
            this.runFlag = true;
            if(this.updater!=null)
                this.updater.start();
        }

        return Service.START_NOT_STICKY;

    }

    public void onDestroy() {
        Log.d(TAG, "OnDestroy");
        super.onDestroy();
        this.runFlag = false;
        this.updater.interrupt();
        this.updater = null;

    }

    private void sendData(final HashMap<String, String> coordinates) {
        Log.i(TAG, "Updateservice aktiv!");
        if (coordinates != null) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    final SharedPreferences sharedPrefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    String mobile = sharedPrefs.getString("prefMobile", null); //$NON-NLS-1$
                    if (mobile != null) {
                        try {
                            CommunicationHandler ch = new CommunicationHandler(sharedPrefs.getString("prefIp", null),
                                    Integer.parseInt(sharedPrefs.getString("prefPort", "999")));
                            ch.sendCoordinates(getApplicationContext(), mobile, coordinates);
                            ch.receiveResponse(ContactResponse.class);
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }
                    }
                }

            }).start();
        }
    }

    public class Updater extends Thread {

        public void run() {

            UpdateService service = UpdateService.this;
            while (service.runFlag) {
                final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                boolean updateServiceEnabled = sharedPrefs.getBoolean("prefUpdateService", true); //$NON-NLS-1$
                
                try {
                    if(!updateServiceEnabled) {
                        Thread.sleep(60000);
                        continue;
                    }
                    Log.i(UpdateService.this.TAG, "Aufgerufen");

                    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                    Criteria criteria = new Criteria();
                    provider = locationManager.getBestProvider(criteria, false);

                    locationManager.requestLocationUpdates(provider, 5000, 500, service, Looper.getMainLooper());

                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        coordinates = new HashMap<String, String>();
                        coordinates.put("latitude", String.valueOf(latitude));
                        coordinates.put("longitude", String.valueOf(longitude));
                        sendData(coordinates);

                        Thread.sleep(delay);

                    }

                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        Toast.makeText(this, Messages.getString("UpdateService.0") + provider, Toast.LENGTH_SHORT).show(); //$NON-NLS-1$

    }

    @Override
    public void onProviderDisabled(String provider) {
        Toast.makeText(this, Messages.getString("UpdateService.1") + provider, Toast.LENGTH_SHORT).show(); //$NON-NLS-1$
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
}
